const express = require('express');
const router = express.Router();
const Tag = require('../models/tag');
const {Op} = require('sequelize');

router.get('/list', async (req, res) => {
    try {
        const tags = await Tag.findAll();
        res.send({
            code: 200,
            data: tags
        });
    } catch (error) {
        console.error('获取标签列表失败:', error);
        res.send({code:500, message: error.message });
    }
})

router.get('/page', async (req, res) => {
    try{
        const {page = 1, pageSize = 10, name = ''} = req.query;
        const offset = (page - 1) * pageSize;
        const where = {};
        if (name && name.trim().length > 0){
            where.name = {
                [Op.like]: `%${name.trim()}%`
            }
        }
        const {count, rows} = await Tag.findAndCountAll({
            where,
            offset: parseInt(offset),
            limit: parseInt(pageSize),
            order: [['id', 'ASC']]}
        );
        res.send({
            code: 200,
            data: rows,
            total: count
        })
    }catch (e) {
        res.send({code:500, message: e.message});
    }
})


router.post('/post', async (req, res) => {
    try {
        const { id, name } = req.body;
        if (!id) {
            // 避免使用 res 作为变量名
            const newTag = await Tag.create({ name });
            res.send({ code: 200, data: newTag, message: '添加成功!' });
        } else {
            const tag = await Tag.findByPk(id);
            tag.name = name;
            await tag.save();
            // 避免使用 res 作为变量名
            res.send({ code: 200, data: tag, message: '修改成功!' });
        }
    } catch (e) {
        res.send({ code: 500, message: e.message });
    }
});

router.delete('/delete', async (req, res) => {
    try{
        const {id} = req.body
        const tag = await Tag.findByPk(id);
        if(!tag){
            res.send({code: 500, message: '数据不存在!'})
        }
        await tag.destroy()
        res.send({code: 200, message: '删除成功!'})

    }catch (e) {
        res.send({code:500, message: e.message});
    }
})

module.exports = router
